package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class HttpServletRequest {
    private Socket socket;
    private Map<String , String> headers = new HashMap<>();
    private String method;
    private String uri;
    private String protocol;
    private String requestURI;//保存uri中?左侧的内容，如果uri中没有"?"则内容与uri一致
    private String queryString;//保存uri中"?"右侧内容，即：参数部分
    //用来保存客户端传递过来的每一组参数
    private Map<String , String> parameters = new HashMap<>();

    public HttpServletRequest(Socket socket) throws IOException, EmptyRequestException {
        this.socket = socket;
        //1.1解析请求行
        parseRequestLine();
        //1.2解析消息头
        parseHeaders();
        //1.3解析消息正文
        parseContent();
    }




    private String readLine() throws IOException {

        InputStream in = socket.getInputStream();//创建输入流读取请求数据

        StringBuilder builder = new StringBuilder();
        int d;
        char pre = 'a', cur = 'a';//用两个字符变量，分别代表当前字符和上一个字符
        while ((d = in.read())!=-1){
            pre = (char)d;//将读取到的字节转换为字符赋值给pre
            if (cur==13&&pre==10){//当上一个字符等于回车，当前字符等于换行时，循环结束
                break;
            }
            builder.append(pre);//将读取的字符拼接到builder中
            cur = pre;//在进行下一次读取前将当前字符赋值给cur，让cur作为上一次读取的字符
        }
        return builder.toString().trim();//转换为字符串类型并去两边的空字符
    }

    private void parseRequestLine() throws IOException, EmptyRequestException {
        String line =readLine();

        if (line.isEmpty()){//如果请求行为空字符串，则说明为空请求
            throw new EmptyRequestException();
        }
        System.out.println(line);
        String[] array = line.split("\\s");
        //将解析行的内容拆分成三部分，分别赋值给三个变量
        method = array[0];
        uri = array[1];
        protocol = array[2];

        //进一步解析uri
        parseUri();

        System.out.println("method:"+method);
        System.out.println("uri:"+uri);
        System.out.println("protocol:"+protocol);
    }

    /**
     * 进一步解析uri
     */
    private void parseUri(){
        String[] data = uri.split("\\?");
        requestURI = data[0];
        if (data.length>1){
            queryString = data[1];
            data = queryString.split("&");
            for (String para : data) {
                String[] paras = para.split("=");
                parameters.put(paras[0],paras.length>1?paras[1]:null);
            }
        }

//        if (uri.contains("?")){
//            requestURI = uri.substring(0,uri.indexOf("?"));
//            queryString = uri.substring(uri.indexOf("?")+1);
//            String[] array = queryString.split("&");
//            for (int i = 0; i < array.length; i++) {
//                String[] array1 = array[i].split("=");
//                if (array1.length <= 1) {
//                    parameters.put(array1[0], null);
//                } else {
//                    parameters.put(array1[0], array1[1]);
//                }
////                String key = array[i].substring(0,array[i].indexOf("="));
////                String value = array[i].substring(array[i].indexOf("=")+1);
////                if (value.isEmpty()){
////                    parameters.put(key , null);
////                }else{
////                  parameters.put(key ,value);
//            //    }
//            }
//        }

        System.out.println("requestURI:"+requestURI);
        System.out.println("queryString:"+queryString);
        System.out.println("parameters:"+parameters);
    }

    private void parseHeaders() throws IOException {
        String line;
        while (!(line = readLine()).isEmpty()){
            String[] array = line.split(":\\s");
            headers.put(array[0],array[1]);
            System.out.println(line);
        }
        System.out.println(headers);
    }

    private void parseContent(){

    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getHeader(String name){
        return headers.get(name);
    }

    public String getRequestURI() {
        return requestURI;
    }

    public String getQueryString() {
        return queryString;
    }

    /**
     * 根据参数名获取对应的参数值
     * @param name
     * @return
     */
    public String getParameter(String name){
        return parameters.get(name);
    }
}
